package config

import (
	"api-gateway-core/common"
	"api-gateway-core/mapping"
	"api-gateway-core/reference"
	"api-gateway-engine/domain/service"
	"fmt"
	"log"
)

// 向注册中心注册当前网关
func appRegister() {
	err := service.DoRegister(Address, GroupId, GatewayId, GatewayName, fmt.Sprintf("%s:%s", GatewayHost, GatewayPort))
	if err != nil {
		log.Println("网关上传失败", err)
		return
	}
	Configuration = common.NewConfiguration(GatewayHost, GatewayPort)
	appPull("")
}

func appPull(systemId string) {

	// 1. 拉取网关配置；每个网关算力都会在注册中心分配上需要映射的RPC服务信息，包括；系统、接口、方法
	applicationSystemRichInfo, err := service.PullApplicationSystemRichInfo(Address, GatewayId, systemId)
	if err != nil {
		log.Println("从配置中心拉取数据错误：", err)
		return
	}
	if applicationSystemRichInfo == nil {
		return
	}
	Configuration.MapperRegistry = reference.NewReferenceRegistry(Configuration)
	for _, applicationSystemVO := range applicationSystemRichInfo.ApplicationSystemList {
		for _, interfaceVO := range applicationSystemVO.InterfaceList {
			// 1.1 创建配置信息加载注册
			Configuration.RegistryConfiguration(applicationSystemVO.SystemRegistry,
				applicationSystemVO.SystemId,
				interfaceVO.InterfaceId,
				interfaceVO.InterfaceVersion)
			// 1.2 注册系统服务接口信息
			for _, methodVO := range interfaceVO.MethodList {
				statement := &mapping.HttpStatement{
					Application:     methodVO.SystemId,
					InterfaceName:   methodVO.InterfaceId,
					ParameterType:   methodVO.ParameterType,
					MethodName:      methodVO.MethodId,
					URI:             methodVO.Uri,
					HttpCommandType: mapping.HttpCommandType(methodVO.HttpCommandType),
					Auth:            methodVO.Auth,
				}
				//log.Println("Configuration添加statement" + statement.MethodName + "-----------------")
				Configuration.AddReference(statement)
			}
		}
	}
}
